package com.carrental.rental.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.carrental.rental.dto.OrderDTO;
import com.carrental.rental.entity.Order;
import com.carrental.rental.mapper.OrderMapper;
import com.carrental.rental.service.OrderService;
import com.carrental.rental.vo.OrderVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import lombok.extern.slf4j.Slf4j;
import com.carrental.rental.client.VehicleClient;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 订单服务实现类
 */
@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private VehicleClient vehicleClient;

    /**
     * 创建订单
     *
     * @param orderDTO 订单DTO
     * @return 订单ID
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createOrder(OrderDTO orderDTO) {
        // 生成订单号
        String orderNo = generateOrderNo();
        
        Order order = new Order();
        BeanUtils.copyProperties(orderDTO, order);
        order.setOrderNo(orderNo);
        order.setStatus(1); // 默认状态为待支付
        order.setCreateTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        
        // 保存订单
        save(order);
        
        return order.getId();
    }

    /**
     * 根据ID获取订单详情
     *
     * @param id 订单ID
     * @return 订单VO
     */
    @Override
    public OrderVO getOrderById(Long id) {
        Order order = getById(id);
        if (order == null) {
            return null;
        }
        
        return convertToVO(order);
    }

    /**
     * 根据订单号获取订单详情
     *
     * @param orderNo 订单号
     * @return 订单VO
     */
    @Override
    public OrderVO getOrderByOrderNo(String orderNo) {
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getOrderNo, orderNo);
        
        Order order = getOne(wrapper);
        if (order == null) {
            return null;
        }
        
        return convertToVO(order);
    }

    /**
     * 分页查询用户订单
     *
     * @param page      分页参数
     * @param userId    用户ID
     * @param status    订单状态
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return 分页订单VO
     */
    @Override
    public Page<OrderVO> pageUserOrders(Page<Order> page, Long userId, Integer status, String startTime, String endTime) {
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getUserId, userId);
        wrapper.eq(status != null, Order::getStatus, status);
        
        if (StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime)) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime start = LocalDateTime.parse(startTime, formatter);
            LocalDateTime end = LocalDateTime.parse(endTime, formatter);
            wrapper.between(Order::getCreateTime, start, end);
        }
        
        wrapper.orderByDesc(Order::getCreateTime);
        
        Page<Order> orderPage = page(page, wrapper);
        
        return convertToVOPage(orderPage);
    }

    /**
     * 分页查询所有订单
     *
     * @param page      分页参数
     * @param orderNo   订单号
     * @param userId    用户ID
     * @param status    订单状态
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return 分页订单VO
     */
    @Override
    public Page<OrderVO> pageOrders(Page<Order> page, String orderNo, Long userId, Integer status, String startTime, String endTime) {
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(orderNo), Order::getOrderNo, orderNo);
        wrapper.eq(userId != null, Order::getUserId, userId);
        wrapper.eq(status != null, Order::getStatus, status);
        
        if (StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime)) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime start = LocalDateTime.parse(startTime, formatter);
            LocalDateTime end = LocalDateTime.parse(endTime, formatter);
            wrapper.between(Order::getCreateTime, start, end);
        }
        
        wrapper.orderByDesc(Order::getCreateTime);
        
        Page<Order> orderPage = page(page, wrapper);
        
        return convertToVOPage(orderPage);
    }

    /**
     * 支付订单
     *
     * @param id 订单ID
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean payOrder(Long id) {
        Order order = getById(id);
        if (order == null) {
            return false;
        }
        
        // 检查订单状态是否为待支付
        if (order.getStatus() != 1) {
            return false;
        }
        
        // 更新订单状态为已支付待取车
        order.setStatus(2);
        order.setPayTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        
        return updateById(order);
    }

    /**
     * 取消订单
     *
     * @param id 订单ID
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean cancelOrder(Long id) {
        Order order = getById(id);
        if (order == null) {
            return false;
        }
        
        // 检查订单状态是否为待支付或已支付待取车
        if (order.getStatus() != 1 && order.getStatus() != 2) {
            return false;
        }
        
        // 更新订单状态为已取消
        order.setStatus(6);
        order.setUpdateTime(LocalDateTime.now());
        
        return updateById(order);
    }

    /**
     * 确认取车
     *
     * @param id 订单ID
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean confirmPickup(Long id) {
        Order order = getById(id);
        if (order == null) {
            return false;
        }
        
        // 检查订单状态是否为已支付待取车
        if (order.getStatus() != 2) {
            return false;
        }
        
        // 更新订单状态为用车中
        order.setStatus(3);
        order.setPickupTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        
        return updateById(order);
    }

    /**
     * 确认还车
     *
     * @param id 订单ID
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean confirmReturn(Long id) {
        Order order = getById(id);
        if (order == null) {
            return false;
        }
        
        // 检查订单状态是否为用车中
        if (order.getStatus() != 3) {
            return false;
        }
        
        // 更新订单状态为已还车待结算
        order.setStatus(4);
        order.setReturnTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        
        return updateById(order);
    }

    /**
     * 完成订单
     *
     * @param id 订单ID
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean completeOrder(Long id) {
        Order order = getById(id);
        if (order == null) {
            return false;
        }
        
        // 检查订单状态是否为已还车待结算
        if (order.getStatus() != 4) {
            return false;
        }
        
        // 更新订单状态为已完成
        order.setStatus(5);
        order.setUpdateTime(LocalDateTime.now());
        
        boolean updated = updateById(order);
        
        // 更新车辆租赁次数
        if (updated) {
            try {
                vehicleClient.updateVehicleRentalCount(order.getVehicleId());
                log.info("已更新车辆租赁次数，车辆ID：{}", order.getVehicleId());
            } catch (Exception e) {
                log.error("更新车辆租赁次数失败，车辆ID：{}，错误：{}", order.getVehicleId(), e.getMessage());
                // 不影响订单完成流程，所以捕获异常但不抛出
            }
        }
        
        return updated;
    }

    /**
     * 生成订单号
     */
    private String generateOrderNo() {
        // 生成格式为：当前时间（年月日时分秒）+ 6位随机数
        String timeStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        String randomStr = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 6);
        return "O" + timeStr + randomStr;
    }

    /**
     * 转换订单实体为VO
     */
    private OrderVO convertToVO(Order order) {
        if (order == null) {
            return null;
        }
        
        OrderVO vo = new OrderVO();
        BeanUtils.copyProperties(order, vo);
        
        // 设置订单状态名称
        vo.setStatusName(getStatusName(order.getStatus()));
        
        // TODO: 调用用户服务获取用户信息
        // TODO: 调用车辆服务获取车辆信息
        // TODO: 调用门店服务获取门店信息
        
        return vo;
    }

    /**
     * 转换订单分页为VO分页
     */
    private Page<OrderVO> convertToVOPage(Page<Order> page) {
        Page<OrderVO> voPage = new Page<>();
        voPage.setCurrent(page.getCurrent());
        voPage.setSize(page.getSize());
        voPage.setTotal(page.getTotal());
        
        List<OrderVO> voList = page.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
        
        voPage.setRecords(voList);
        return voPage;
    }

    /**
     * 获取订单状态名称
     */
    private String getStatusName(Integer status) {
        if (status == null) {
            return "";
        }
        
        switch (status) {
            case 1:
                return "待支付";
            case 2:
                return "已支付待取车";
            case 3:
                return "用车中";
            case 4:
                return "已还车待结算";
            case 5:
                return "已完成";
            case 6:
                return "已取消";
            default:
                return "未知状态";
        }
    }
} 